<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\library\QRCode;
use addons\qingdongams\model\Companys;
use addons\qingdongams\model\ConsumeDetail;
use addons\qingdongams\model\Equipment;
use addons\qingdongams\model\Event;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Flow;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use addons\qingdongams\model\StaffSignIn;
use addons\qingdongams\model\Workorder as WorkorderModel;
use addons\qingdongams\model\WorkorderLogistics;
use addons\qingdongams\model\CustomerProduct;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\WorkorderProgress;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Db;
use think\Exception;
use think\Log;
use think\Response;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 工单
 */
class Workorder extends StaffApi
{
    protected $noNeedLogin = ['qrcode', 'notifyorder', 'returnorder'];
    protected $noNeedRight = [];
    //提交  0待指派
    //已指派 1
    //维修失败，已提交售后领导和销售创建人  2
    //维修成功，等待录入费用 3
    //费用审核通过，待支付工单 4
    //工单支付成功，待录入物流信息 5
    //销售根据评估结果，继续生产，即继续维修  6
    //费用待审核  7
    //维修结束，打样申请结束  9

    //获取工单列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        //
        $where = [];
        if (isset($params['name']) && $params['name']) {//查询名称
            $where['title|workorder_number'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['customer_id']) && $params['customer_id']) {//所属客户
            $where['customer_id'] = $params['customer_id'];
        }

        if (isset($params['status']) && $params['status']) {//状态
            $where['status'] = $params['status'];
            if ($params['status'] == 3) {
                $where['status'] = ['in', [3, 9]];
            }
        }
        if (isset($params['complete_status'])) {//完成状态
            if ($params['complete_status'] == 1) {//未完成
                $where['status'] = ['in', [0, 1, 2]];
            } elseif ($params['complete_status'] == 2) {//待指派
                $where['status'] = 0;
            } elseif ($params['complete_status'] == 3) {//进行中
                $where['status'] = ['in', [1, 2]];
            } elseif ($params['complete_status'] == 4) {//异常工单
                $where['status'] = ['in', [0, 1, 2]];
                $where['is_pause|is_timeout'] = 1;
            }
        }
        $whereStaff = [];
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $whereStaff['create_staff_id|owner_staff_id'] = $params['staff_id'];
        } else {
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我工单
                    $whereStaff['create_staff_id|owner_staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属负责的工单
                    $whereStaff['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
                }
            } else {
                $whereStaff = function ($query) {
                    $query->where('create_staff_id|owner_staff_id', 'in', Staff::getMyStaffIds());
                };
            }
        }

        //异常工单
        if (isset($params['is_yichang']) && $params['is_yichang']) {
            $where['is_pause|is_timeout'] = 1;
        }
        if (isset($params['workorder_type']) && $params['workorder_type']) {
            $where['workorder_type'] = $params['workorder_type'];
        }
        if (isset($params['createtime']) && $params['createtime']) {
            $times = setTimes($params['createtime'], 'time');
            $where['createtime'] = ['between', $times];
        }
        if (isset($params['end_time']) && $params['end_time']) {
            $times = setTimes($params['end_time'], 'time');
            $where['end_time'] = ['between', $times];
        }
        if (isset($params['comment_score']) && $params['comment_score']) {
            $where['comment_score'] = 5;
        }
        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            if (empty($city)) {
                $where['address|address_detail'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address|address_detail'] = ['like', "%{$city}%"];
            } else {
                $where['address|address_detail'] = ['like', "%{$area}%"];
            }
        }
        if (isset($params['id_list'])) {//日志 查询id列表
            $where = [];
            $whereStaff = [];
            $where['id'] = ['in', explode(',', $params['id_list'])];
        }
        $list = WorkorderModel::where($where)->where($whereStaff)->with([
            'customer',
            'ownerStaff',
            'contacts', 'file'
        ])->field('deletetime,updatetime', true)->order('createtime desc')->paginate($limit);

        $this->success('请求成功', $list);
    }

    //获取回访工单列表
    public function getVisitList()
    {
        $limit = input("limit/d", 10);
        $is_visit = input('is_visit', 0);
        $params = $this->request->post();
        //
        $where = [];
        if (isset($params['name']) && $params['name']) {//查询名称
            $where['title|workorder_number'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['customer_id']) && $params['customer_id']) {//所属客户
            $where['customer_id'] = $params['customer_id'];
        }

        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            if (empty($city)) {
                $where['address|address_detail'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address|address_detail'] = ['like', "%{$city}%"];
            } else {
                $where['address|address_detail'] = ['like', "%{$area}%"];
            }
        }
        $where['status'] = 3;
        $where['is_visit'] = $is_visit;
        $where['workorder_type'] = ['in', WorkorderModel::getVisitType()];
        $list = WorkorderModel::where($where)->with([
            'customer',
            'ownerStaff',
            'contacts'
        ])->field('deletetime,updatetime', true)->order('createtime desc')->paginate($limit);

        $this->success('请求成功', $list);
    }

    //获取收款工单列表
    public function getFinancialList()
    {
        $limit = input("limit/d", 10);
        $is_financial_audit = input('is_financial_audit', 0);
        $params = $this->request->post();
        //
        $where = [];
        if (isset($params['name']) && $params['name']) {//查询名称
            $where['title|workorder_number'] = ['like', "%{$params['name']}%"];
        }
        if (isset($params['customer_id']) && $params['customer_id']) {//所属客户
            $where['customer_id'] = $params['customer_id'];
        }

        if (isset($params['prov']) && !empty(trim($params['prov']))) {//省市区筛选
            $prov = trim($params['prov']);
            $city = trim($params['city']);
            $area = trim($params['area']);
            if (empty($city)) {
                $where['address|address_detail'] = ['like', "%{$prov}%"];
            } elseif (empty($area)) {
                $where['address|address_detail'] = ['like', "%{$city}%"];
            } else {
                $where['address|address_detail'] = ['like', "%{$area}%"];
            }
        }
        $where['status'] = 3;
        $where['is_pay'] = 1;//收款工单
        $where['is_financial_audit'] = $is_financial_audit;
        $list = WorkorderModel::where($where)->with([
            'customer',
            'ownerStaff',
            'contacts'
        ])->field('deletetime,updatetime', true)->order('createtime desc')->paginate($limit);

        $this->success('请求成功', $list);
    }

    //添加工单
    public function addWorkorder()
    {
        $params = $this->request->post();
        // 表单验证
        if (($result = $this->qingdongamsValidate($params,get_class(), 'create')) !== true) {
            $this->error($result);
        }
        if (WorkorderModel::where([
            'workorder_number' => $params['workorder_number'],
        ])->find()) {
            $this->error('工单编号已存在');
        }
        try {
            $result = WorkorderModel::createWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加工单成功');
        }
    }


    //获取工单编号
    public function getWorkorderNumber()
    {
        $this->success('请求成功', ['number' => WorkorderModel::getWorkorderNumber()]);
    }

    //获取品质异常工单编号
    public function getBadWorkorderNumber()
    {
        $this->success('请求成功', ['number' => 'Y' . date('ymd') . rand(100, 999)]);
    }


    //编辑工单
    public function editWorkorder()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('修改工单信息不存在');
        }

        Db::startTrans();
        try {
            $result = WorkorderModel::updateWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改工单信息成功');
    }

    //获取工单详情
    public function getWorkorderDetail()
    {
        $id = input('id');
        $workorder = WorkorderModel::where(['id' => $id])->with(['createStaff',
            'contacts', 'customer', 'ownerStaff', 'file', 'getevent', 'visit'])->find();
        if (empty($workorder)) {
            $this->error('参数不存在');
        }
        $workorder = $workorder->toArray();
        if ($workorder['check_status'] == 1) {//审核中
            $workorder['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::WORKORDER_TYPE, $id);
        } else {
            $workorder['is_examine'] = 0;
        }
        if (empty($workorder['contacts'])) {
            $workorder['contacts'] = \addons\qingdongams\model\Contacts::where(['customer_id' => $workorder['customer_id']])->order('is_major desc')->field('id,customer_id,name,mobile,mobilecode,region')->find();

        }
        $workorder['is_revoke'] = 0;
        $workorder['is_operation'] = 0;
        $workorder['is_operation_visit'] = 0;
        $workorder['is_financial'] = 0;
        $workorder['is_leader'] = 0;
        if ($workorder['create_staff_id'] == $this->auth->id || in_array($workorder['create_staff_id'], Staff::getLowerStaffId())) {
            //是否可以撤销
            $workorder['is_revoke'] = 1;
        }
        //是否可以录入费用-是否可以回款
        $workorder['is_leader'] = 1;
        $workorder['is_leader'] = 1;
        if ($workorder['workorder_type'] == '产品发货' ) {
            //TODO 是否可以操作 售后部不能操作发货工单
            $workorder['is_operation'] = 0;
            $workorder['is_revoke'] = 0;
        }
        if (in_array($workorder['workorder_type'], ['产品发货', '设计工单'])) {
            //业务部领导可以操作发货工单 和 发货工单
            $workorder['is_leader'] = 1;
        }
        if ($workorder['owner_staff_id'] == $this->auth->id) {
            //是否可以操作
            $workorder['is_operation'] = 1;
        }
        if (in_array($workorder['workorder_type'],WorkorderModel::getVisitType()) && $workorder['status'] == 3) { //操作回访
            $workorder['is_operation_visit'] = 1;
        }
        if ($workorder['status'] == 3 && $workorder['is_pay'] == 1 && $workorder['is_financial_audit'] == 0) { //是否财务审核
            $workorder['is_financial'] = 1;
        }
        if ($workorder['customer_product_id']) {
            $customer_product_ids = explode(',', $workorder['customer_product_id']);
            $workorder['customer_product'] = CustomerProduct::where(['id' => ['in', $customer_product_ids]])->with(['product'])->select();

            //是否可以操作物流
            $workorder['is_operation_logistics'] = 0;

            foreach ($workorder['customer_product'] as $k => $v) {
                if (!empty($v['number'])) {
                    $workorder['is_operation_logistics'] = 1;
                }
            }
        }
        if ($workorder['workorder_type'] == '上门维修' || $workorder['workorder_type'] == '返厂维修') {
            $workorder['peisong'] = WorkorderModel::where(['relation_workorder_id' => $id, 'workorder_type' => '配件配送'])->select();
            $workorder['anzhuang'] = WorkorderModel::where(['relation_workorder_id' => $id, 'workorder_type' => '配件安装'])->select();

        }
        if ($workorder['flow_staff_ids']) {
            $workorder['flow_staff'] = Staff::where(['id' => ['in', $workorder['flow_staff_ids']],'status'=>1])->field('id,name,img')->select();
        }

        //是否可以操作完成
        $workorder['is_operation_end'] = 0;
        if (in_array($workorder['status'], [0, 1])) {
            $workorder['is_operation_end'] = 1;
        }
        Message::setRead(Message::WORKORDER_TYPE, $id, $this->auth->id);
        Message::setRead(Message::WORKORDER_RECEIVABLES, $id, $this->auth->id);
        $this->success('请求成功', $workorder);
    }

    //指派负责人
    public function assign_order()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        $desc = input('desc');
        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('工单信息不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::assignWorkorder($id, $staff_id, $desc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('指派成功');
    }

    //转派工单
    public function transfer()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        $desc = input('desc');
        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('工单信息不存在');
        }
        if ($row['owner_staff_id'] == $staff_id) {
            $this->error('不能将工单转派给原负责人');
        }

        Db::startTrans();
        try {
            WorkorderModel::transferWorkorder($id, $staff_id, $desc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('转派成功');
    }

    //接受工单
    public function accept_order()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('参数不能为空');
        }
        $row = WorkorderModel::where(['id' => $params['id']])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        Db::startTrans();
        try {
            $params['workorder_type'] = $row['workorder_type'];
            WorkorderModel::acceptWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('接受工单成功');
    }

    //开始工单
    public function start_order()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('参数不能为空');
        }
        if (empty($params['lng']) || empty($params['lat']) || empty($params['location'])) {
          //  $this->error('定位地理位置错误');
        }
        $row = WorkorderModel::where(['id' => $params['id'], 'status' => 2])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::startWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('开始工单成功');
    }

    //录入零件
    public function input_parts()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('参数不能为空');
        }


        $row = WorkorderModel::where(['id' => $params['id']])->find();
        if (empty($row)) {
            $this->error('工单不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::inputParts($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('录入成功');
    }

    //到达签到
    public function addSign()
    {
        $params = $this->request->post();
        $id = input('id');
        $desc = input('desc', '');

        $where = ['id' => $id];
        $workorder = WorkorderModel::where($where)->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::workorderSign($id, $desc, $params);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }

    //完成工单
    public function complete()
    {
        $params = $this->request->post();
        $id = input('id');
        $desc = input('desc');


        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('工单信息不存在');
        }
        if ($row['is_pause'] == 1) {
            $this->error('工单暂停中');
        }
        if ($params['discount_money'] ?? 0 > 0) {
            if (empty($params['flow_staff_ids'])) {
                $this->error('工单审批人不能为空');
            }
        }
        Db::startTrans();
        try {

            WorkorderModel::completeWorkorder($id, $desc, $params);
            if ($row['workorder_type'] == '产品发货') {//送达待安装
                CustomerProduct::where(['id' => ['in', $row['customer_product_id']]])->update([
                    'status' => 2
                ]);
            }
            //协助任务完成
            Event::where(['relation_type' => 'workorder', 'relation_id' => $row['id'], 'type' => 4])->update(['status' => 2]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('工单完结成功');
    }

    //填写维修结果
    public function repair_result()
    {
        $params = $this->request->post();
        $id = input('id');

        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('工单信息不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::repairResult($id, $params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交成功');
    }

    //录入工单费用
    public function enterWorkorderMoney()
    {
        $params = $this->request->post();
        $id = input('id');

        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('工单信息不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::enterWorkorderMoney($id, $params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交成功');
    }

    //编辑优惠金额
    public function editDiscountMoney()
    {
        $id = input('id');
        $is_charge = input('is_charge', 0);//1 收费     2不收费
        $discount_money = input('discount_money', 0);
        $discount_desc = input('discount_desc', 0);
        if (empty($id)) {
            $this->error('参数错误');
        }
        $row = WorkorderModel::where(['id' => $id])->find();
        Db::startTrans();
        try {
            $money = sprintf('%.2f', $row['total_money'] - $discount_money);
            $update = [
                'is_charge' => $is_charge,
                'discount_money' => $discount_money,
                'money' => $money,
                'discount_desc' => $discount_desc
            ];
            //设置产品编号
            WorkorderModel::where(['id' => $id])->update($update);
            if ($is_charge == 2) {

                $content = '设置工单费用为[不收费]';
            } else {
                $content = '编辑优惠金额为[' . $discount_money . ']';
            }
            $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $params['relation_id'] = $id;
            $params['relation_process'] = '编辑优惠金额';
            //创建跟进记录
            StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改工单信息成功');
    }

    //取消测试/继续测试
    public function isContinueTest()
    {
        $is_continue = input('is_continue');
        $id = input('id');
        Db::startTrans();
        try {
            WorkorderModel::continueTest($id, $is_continue);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('请求成功');
    }

    //获取支付类型
    public function getPayType()
    {
        $data = ['现金', '公户', '微信', '其他'];
        $this->success('请求成功', $data);
    }

    //获取微信支付二维码
    public function getPayOrder()
    {
        $id = input('id');
        $workorder = WorkorderModel::where(['id' => $id])->find();
        if (empty($workorder)) {
            $this->error('工单信息不存在');
        }
        $params = [
            'amount' => $workorder['money'],
            'orderid' => $workorder['workorder_number'],
            'type' => "wechat",
            'method' => "scan",//支付二维码
            'title' => $workorder['title'],
        ];
        //回调链接
        $params['notifyurl'] = $this->request->root(true) . '/addons/qingdongams/workorder/notifyorder';
        $params['returnurl'] = $this->request->root(true) . '/addons/qingdongams/workorder/returnorder';
        //如果有安装支付插件，则调用插件的生成方法
        if (class_exists("\addons\epay\library\Service")) {
            $result =\addons\epay\library\Service::submitOrder($params);
            $this->success('请求成功', $result);
        }else{
            $this->error('未安装支付相关插件');
        }

    }

    /**
     * 支付成功，仅供开发测试
     */
    public function notifyorder()
    {
        $paytype = $this->request->param('paytype');
        Log::error('支付回调:' . json_encode($_REQUEST));
        if (class_exists("\addons\epay\library\Service")) {
            $pay =\addons\epay\library\Service::checkNotify($paytype);
        }else{
            $this->error('未安装支付相关插件');
        }
        if (!$pay) {
            Log::error('签名验证失败:' . json_encode($pay));
            return '签名错误';
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $transaction_id = $data['transaction_id'];
            $find = WorkorderModel::where(['workorder_number' => $out_trade_no, 'pay_order' => $transaction_id])->find();
            if (empty($find)) {
                Log::error('未查询到订单:' . json_encode($out_trade_no));
                return $pay->success();
            }
            $result = WorkorderModel::where(['id' => $find['id']])->update([
                'status' => 3,
                'pay_type' => '微信',
                'pay_order' => $transaction_id,
                'pay_time' => time()]);
            if ($result == false) {
                throw new Exception('错误');
            }
            //你可以在此编写订单逻辑
        } catch (Exception $e) {

            return 'error';
        }
        return $pay->success();
    }

    //支付订单 去结算
    public function pay_order()
    {
        $id = input('id');
        $pay_type = input('pay_type', '');
        $pay_files = input('pay_files', '');
        if (empty($pay_type)) {
            $this->error('支付类型不能为空');
        }
        if (empty($pay_files)) {
            $this->error('支付凭证不能为空');
        }
        $row = WorkorderModel::where(['id' => $id])->find();
        if (empty($row)) {
            $this->error('订单不存在');
        }
        if ($row['is_pay'] == 1) {
            $this->error('订单已支付');
        }
        $update = ['is_pay' => 1, 'pay_time' => time(), 'pay_type' => $pay_type, 'pay_files' => $pay_files];
        //TODO 工单费用审核那里也有相同判断
        if ($row['workorder_type'] == '返厂维修') {
            $update['process'] = 5;
        } else if (in_array($row['workorder_type'], ['上门维修', '电话售后', '配件安装'])) {
            $update['status'] = 3;
        }
        if ($row['is_pay'] == 1) {
            //发送通知
            Message::addMessage(Message::WORKORDER_TYPE, $id, 1, $this->auth->id, '《' . $row->title . '》任务已完成，请您及时确认回款情况！');
        }
        $result = WorkorderModel::where(['id' => $id])->update($update);
        if (empty($result)) {
            $this->error('修改信息失败');
        }
        if (isset($update['status']) && $update['status'] == 3) {
            //工单完成
            WorkorderModel::setComplete($id);
        }

        $content = '支付维修费用成功';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['files'] = $params['files'] ?? '';
        $params['relation_process'] = '支付费用';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        $this->success('支付订单成功');
    }

    //财务确认收款
    public function financial_audit()
    {
        $workorder_id = input('workorder_id', 0, 'intval');
        if (empty($workorder_id)) {
            $this->error('参数不能为空');
        }
        WorkorderModel::financialAudit($workorder_id);
        $this->success('确认收款成功');
    }

    //获取工单进度
    public function getLogs()
    {
        $workorder_id = input('workorder_id', 0, 'intval');
        $limit = input('limit', 10);
        $where = [
            'relation_type' => StaffSignIn::WORKORDER_TYPE,
        ];
        if ($workorder_id) {
            $where['relation_id'] = $workorder_id;
        }

        $staffSign = StaffSignIn::where($where)->with(['staff', 'customer'])->order('id desc')->paginate($limit);

        //标记 日程已读
        Message::where([
            'relation_type' => Message::RECORD_TYPE,
            'to_staff_id' => $this->auth->id,
            'status' => 0
        ])->update(['read_time' => time(), 'status' => 1]);

        $this->success('请求成功', $staffSign);
    }

    //添加工单备注
    public function addLog()
    {
        $params = $this->request->post();
        if (empty($params['id']) || empty($params['desc'])) {
            $this->error('参数不能为空');
        }
        if (empty($params['lng']) || empty($params['lat']) || empty($params['location'])) {
          //  $this->error('定位地理位置错误');
        }
        $row = WorkorderModel::get($params['id']);
        if (empty($row)) {
            $this->error('工单不存在');
        }
        try {
            $content = $params['desc'];

            $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $params['relation_id'] = $row['id'];
            //创建跟进记录
            StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('添加工单备注成功');
    }

    //设置产品编号
    public function setCustomerProductNumber()
    {
        $workorder_id = input('workorder_id');
        $product = input('product/a');
        $params = $this->request->post();

        try {
            Db::startTrans();

            if (!empty($product)) {
                foreach ($product as $v) {
                    if (empty($v['id']) || empty($v['number'])) {
                        throw new Exception('产品编号不能为空');
                    }
                    $hasBing = CustomerProduct::where(['id' => $v['id']])->find();
                    if (!empty($hasBing['number'])) {
                        $logicStatus = CustomerProduct::alias('c')->where(['number' => $hasBing['number']])->join('qingdongams_workorder w', 'w.customer_product_id=c.id', 'left')->field('w.id,w.process')->find();
                        if ($logicStatus['process'] >= 3) {
                            throw new Exception('产品编号[' . $hasBing['number'] . ']已配送,编号[' . $v['number'] . ']不能配送');
                        }
                        // 如果已经绑定，则原先设备 解绑
                        Equipment::where(['number' => $hasBing['number']])->update(['binding_status' => 1, 'cus_pro_id' => 0]);
                    }
                    CustomerProduct::where(['id' => $v['id']])->update(['number' => $v['number'], 'file_ids' => $v['file_ids'] ?? '']);
                }
            }
            unset($params['product']);
            WorkorderModel::setProductNumber($workorder_id, $params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('设置产品编号成功');
    }


    //设置配件配送信息
    public function setCustomerPartsNumber()
    {
        $workorder_id = input('workorder_id');
        $params = $this->request->post();

        try {
            Db::startTrans();


            WorkorderModel::setPartsNumber($workorder_id, $params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交配送信息成功');
    }


    //获取客户地址
    public function getCustomerAddress()
    {
        $customer_id = input('customer_id');
        $address = \addons\qingdongams\model\Customer::where(['id' => $customer_id])->field('id,address,address_detail,lng,lat')->find();
        $this->success('请求成功', $address);
    }

    //添加物流信息
    public function addLogistics()
    {
        $title = input('title');//
        $workorder_id = input('workorder_id');//工单id
        $number = input('number');//物流编号
        $company = input('company');//物流方式
        $senderPhone = input('sender_phone');//发货人手机号 后四位
        $receiverPhone = input('receiver_phone');//发货人手机号 后四位
        $product_ids = input('product_ids');//产品id
        $type = input('type');//
        $money = input('money');//
        $file_ids = input('file_ids');
        if ($type == '物流配送') {

            if (empty($number)) {
                $this->error('物流编号不能为空');
            }
        }
        $workorder = WorkorderModel::where(['id' => $workorder_id])->find();
        if (empty($workorder)) {
            $this->error('工单不能为空');
        }
        $params = [
            'title' => $title,
            'customer_id' => $workorder['customer_id'],
            'workorder_id' => $workorder_id,
            'number' => $number,
            'file_ids' => $file_ids,
            'company' => $company,
            'type' => $type,
            'money' => $money,
            'receiver_phone' => $senderPhone,
            'sender_phone' => $receiverPhone,
            'product_ids' => $product_ids,
            'current_status' => json_encode(['text' => date('m-d H:i'), 'desc' => '提交物流信息'], JSON_UNESCAPED_UNICODE),
            'content' => json_encode([['text' => date('m-d H:i'), 'desc' => '提交物流信息']], JSON_UNESCAPED_UNICODE),
        ];
        $customerInfo = Customer::where(['id' => $workorder['customer_id']])->find();
        try {
            Db::startTrans();
            WorkorderLogistics::createLogistics($params);
            $product_ids = explode(',', $product_ids);
            foreach ($product_ids as $id) {
                if ($workorder['is_install'] == 1) {
                    if ($workorder['workorder_type'] == '配件配送') {
                        //获取售后助理
                        $addWorkorder = [
                            'workorder_number' => WorkorderModel::getWorkorderNumber(),
                            'workorder_type' => '配件安装',
                            'title' => '配件安装',
                            'customer_id' => $customerInfo['id'],
                            'contacts_id' => $workorder['contacts_id'],
                            'address' => $customerInfo['address'],
                            'address_detail' => $customerInfo['address_detail'],
                            'lng' => $customerInfo['lng'],
                            'lat' => $customerInfo['lat'],
                            'parts' => $workorder['parts'],
                            'priority' => '一般',
                            'owner_staff_id' => $workorder['owner_staff_id'],
                            'desc' => '自动生成安装工单'
                        ];
                        WorkorderModel::createWorkorder($addWorkorder);
                    } else {
                        $addWorkorder = [
                            'workorder_number' => WorkorderModel::getWorkorderNumber(),
                            'workorder_type' => '上门安装',
                            'title' => '上门安装',
                            'customer_id' => $customerInfo['id'],
                            'contacts_id' => $workorder['contacts_id'],
                            'address' => $customerInfo['address'],
                            'address_detail' => $customerInfo['address_detail'],
                            'lng' => $customerInfo['lng'],
                            'lat' => $customerInfo['lat'],
                            'customer_product_id' => $id,
                            'priority' => '一般',
                            'owner_staff_id' =>  $workorder['owner_staff_id'],
                            'desc' => '自动生成安装工单'
                        ];
                        WorkorderModel::createWorkorder($addWorkorder);
                    }

                }
            }


            WorkorderModel::setLogistics($workorder_id, $product_ids);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('添加物流信息成功');
    }

    //修改物流信息
    public function editLogistics()
    {
        $id = input('id');//
        $title = input('title');//
        $number = input('number');//物流编号
        $company = input('company');//物流方式
        $senderPhone = input('sender_phone');//发货人手机号 后四位
        $receiverPhone = input('receiver_phone');//发货人手机号 后四位
        $product_ids = input('product_ids');//产品id
        $type = input('type');//
        $money = input('money');//
        $file_ids = input('file_ids');


        $logistics = WorkorderLogistics::where(['id' => $id])->find();
        if (empty($logistics)) {
            $this->error('物流信息不存在');
        }
        $params = [
            'id' => $id,
            'type' => $type,
            'title' => $title,
            'number' => $number,
            'file_ids' => $file_ids,
            'company' => $company,
            'product_ids' => $product_ids,
            'sender_phone' => $senderPhone,
            'receiver_phone' => $receiverPhone,
            'money' => $money,
        ];
        try {
            Db::startTrans();
            WorkorderLogistics::updateLogistics($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改物流信息成功');
    }


    //获取列表
    public function getWorkorderProduct()
    {
        $workorder_id = input("workorder_id", 0);
        $where = ['id' => $workorder_id];
        $workorder = WorkorderModel::where($where)->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        $customer_product_ids = explode(',', $workorder['customer_product_id']);
        $customer_product = CustomerProduct::where(['id' => ['in', $customer_product_ids], 'status' => 0])->with(['product'])->select();

        $this->success('请求成功', $customer_product);
    }

    //获取物流信息
    public function getLogisticsList()
    {
        $workorder_id = input('workorder_id', '');
        $where = [];
        if (empty($workorder_id)) {
            $this->error('工单id不能为空');
        }
        $where['workorder_id'] = $workorder_id;
        $workorders = WorkorderLogistics::where($where)->select();

        $this->success('请求成功', $workorders);
    }

    //邀请其他部门协助
    public function addEvent()
    {
        $id = input('id');
        $staff_id = input('staff_id');
        $title = input('title');//
        $remark = input('remark');

        try {
            $params['staff_id'] = $staff_id;
            $params['title'] = $title;
            $params['remark'] = $remark;
            $params['type'] = 4;//协助任务
            $params['status'] = 1;//
            $params['relation_type'] = 'workorder';
            $params['relation_id'] = $id;

            $result = Event::createEvent($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加日程成功');
        }
    }

    //协助任务 多条
    public function addEvents()
    {
        $data = input('data/a');
        if (empty($data)) {
            $this->error('请添加协助人');
        }
        try {
            $staffIds = [];
            foreach ($data as $item) {
                $staffIds[] = $item['staff_id'];
                $params = [
                    'staff_id' => $item['staff_id'] ?? 0,
                    'title' => $item['title'] ?? '协助任务',
                    'remark' => $item['remark'] ?? '',
                    'type' => 4,//协助任务
                    'status' => 1,//
                    'relation_type' => 'workorder',
                    'relation_id' => $item['id'],

                ];
                $result = Event::createEvent($params);
            }
            $row = WorkorderModel::get($item['id']);

            if ($row['status'] == 1) {
                $update = ['status' => 2];
                if ($row['workorder_type'] == '设计工单') {
                    $update['process'] = 1;
                }
                $row->save($update);
                Event::where(['relation_type' => 'workorder', 'relation_id' => $item['id'], 'type' => 1])
                    ->update(['status' => 1]);
            }
            $names = Staff::where(['id' => ['in', $staffIds],'status'=>1])->column('name');
            $content = "邀请" . implode(',', $names) . "协作";
            $data['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $data['relation_id'] = $row['id'];
            $data['relation_process'] = '邀请协作';
            //创建跟进记录
            StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加协助任务成功');
        }
    }

    //添加电话沟通记录
    public function addMobileLog()
    {
        $params = $this->request->post();

        $is_complete = input('is_complete', 0);//是否解决 1 已解决  0 未解决
        $id = input('id');
        $desc = input('desc');
        if ($is_complete == 1) {
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            Db::startTrans();
            try {
                $params['is_mobile'] = 1;
                WorkorderModel::completeWorkorder($id, $desc, $params);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('工单完结成功');
        } else {
            $row = WorkorderModel::where(['id' => $id])->find();
            if (empty($row)) {
                $this->error('工单信息不存在');
            }
            if (empty($params['mobile_result'])) {
                $this->error('电话结果不能为空');
            }
            $update = [];

            $update['mobile_result'] = $params['mobile_result'] ?? '';//电话结果  1 已解决 11 上门服务 12 返厂维修
            $update['logistics_type'] = $params['logistics_type'] ?? '';
            $update['is_mobile'] = 1;
            $update['status'] = 2;
            $result = WorkorderModel::where(['id' => $id])->update($update);

            $this->success('提交成功');
        }


    }

    //获取快递公司
    public function getCompanys()
    {
        $companys = Companys::where([])->column('com', 'no');

        $this->success('请求成功', $companys);
    }


    //暂停工单
    public function suspendWorkorder()
    {
        $id = input('id');
        $params = $this->request->post();
        if (empty($params['id']) || empty($params['desc'])) {
            $this->error('参数不能为空');
        }
        if (empty($params['lng']) || empty($params['lat']) || empty($params['location'])) {
        //    $this->error('定位地理位置错误');
        }

        $workorder = WorkorderModel::where(['id' => $id])->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        if ($workorder['status'] != 2) {
            $this->error('工单状态错误');
        }
        if (WorkorderModel::save(['is_pause' => 1], ['id' => $id]) != true) {
            $this->error('操作失败');
        }

        $content = $params['desc'];
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $workorder['id'];
        $params['relation_process'] = '暂停工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($workorder['customer_id'], $content, $params);

        $this->success('暂停工单成功');
    }

    //继续工单
    public function continueWorkorder()
    {
        $id = input('id');
        $params = $this->request->post();
        if (empty($params['id']) || empty($params['desc'])) {
            $this->error('参数不能为空');
        }
        if (empty($params['lng']) || empty($params['lat']) || empty($params['location'])) {
        //    $this->error('定位地理位置错误');
        }

        $workorder = WorkorderModel::where(['id' => $id])->find();
        if (empty($workorder)) {
            $this->error('工单不存在');
        }
        if ($workorder['is_pause'] != 1) {
            $this->error('工单状态错误');
        }
        if (WorkorderModel::save(['is_pause' => 0], ['id' => $id]) != true) {
            $this->error('操作失败');
        }

        $content = $params['desc'];
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $workorder['id'];
        $params['relation_process'] = '继续工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($workorder['customer_id'], $content, $params);

        $this->success('继续工单成功');
    }

    //关闭工单
    public function cancelWorkorder()
    {
        $id = input('id');
        $desc = input('desc', '');
        if (empty($id)) {
            $this->error('id不能为空');
        }
        if (empty($desc)) {
            $this->error('备注不能为空');
        }

        Db::startTrans();
        try {
            $result = WorkorderModel::cancelWorkorder($id, $desc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('终止成功');
    }

    //撤销工单
    public function revokeWorkorder()
    {
        $id = input('id');
        $desc = input('desc', '');
        if (empty($id)) {
            $this->error('id不能为空');
        }
        if (empty($desc)) {
            $this->error('备注不能为空');
        }
        $workorder=WorkorderModel::get($id);
        if($workorder['owner_staff_id'] != $this->auth->id){
            $this->error('只有负责人才能撤销工单');
        }
        Db::startTrans();
        try {
            $result = WorkorderModel::revokeWorkorder($id, $desc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('撤销成功');
    }

    //回访工单工单
    public function visitWorkorder()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }

        Db::startTrans();
        try {
            $result = WorkorderModel::visitWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回访成功');
    }

    //回执工单
    public function receiptWorkorder()
    {
        $params = $this->request->post();
        if (empty($params['id'])) {
            $this->error('id不能为空');
        }
        if (empty($params['receipt_file_ids'])) {
            $this->error('回执单不能为空');
        }
        if (empty($params['receipt_date'])) {
            $this->error('回执时间不能为空');
        }

        Db::startTrans();
        try {
            $result = WorkorderModel::receiptWorkorder($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回执成功');
    }

    //签名
    public function autograph()
    {
        $id = input('id');
        $autograph_url = input('autograph_url', '');
        if (empty($id)) {
            $this->error('id不能为空');
        }

        Db::startTrans();
        try {
            $result = WorkorderModel::autograph($id, $autograph_url);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('签字成功');
    }

    //添加品质异常单进度
    public function addProgress()
    {
        $params = $this->request->post();
         $result=WorkorderModel::addProgress($params);
        $this->success('操作成功');
    }

    //获取品质异常单进度列表
    public function getProgressList()
    {
        $workorder_id = input('workorder_id');
        $model = new WorkorderProgress();
        $list = $model->where(['workorder_id' => $workorder_id])->column('*', 'create_staff_id');
        $workorder = WorkorderModel::get($workorder_id);
        $flow_staff_ids = explode(',', trim($workorder['flow_staff_ids'], ','));
        $check_staff_ids = explode(',', trim($workorder['check_staff_ids'], ','));
        $staffs = Staff::where(['id' => ['in', $flow_staff_ids],'status'=>1])->field('id,name,img,mobile')->select();
        $staffs = collection($staffs)->toArray();
        foreach ($staffs as $k => $v) {
            if (in_array($v['id'], $check_staff_ids)) {
                $v['is_check'] = 1;
                $progress = $list[$v['id']] ?? [];
                if($progress){
                    $progress['createtime'] = date('Y-m-d H:i:s',$progress['createtime']);
                }
                $v['progress'] = $progress;
            } else {
                $v['is_check'] = 0;
            }
            $staffs[$k] = $v;
        }

        $this->success('请求成功', $staffs);
    }

    //下载配件报价单
    public function downloadWorkorder()
    {
        $id = input('id');
        $type = input('type', 'word');
        $workorder = WorkorderModel::where(['id' => $id])
            ->with(['customer', 'contacts','ownerStaff'])->find();
        if (empty($workorder)) {
            $this->error('不能为空');
        }

        $workorder = $workorder->toArray();

        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/peijian.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);


        $tmp->setValue('number', $workorder['workorder_number']);//订单编号
        $tmp->setValue('customer', $workorder['customer']['name']);//乙方
        $tmp->setValue('name', $workorder['contacts']['name']);//乙方
        $tmp->setValue('mobile', $workorder['contacts']['mobile']);//乙方
        $tmp->setValue('date', $workorder['createtime']);//签订时间
        $use_parts = $workorder['use_parts'];
        $rda = [];
        foreach ($use_parts as $v) {
            if ($v['is_charge'] == 1) {
                $rda[] = $v;
            }
        }

        $rows = count($rda);//总行数
        $pay_service = $workorder['pay_service'];
        $tmp->cloneRow('one', $rows + count($pay_service));//复制行
        for ($i = 0; $i < $rows; $i++) {
            $tmp->setValue("one#" . ($i + 1), $i + 1);//名称
            $tmp->setValue("two#" . ($i + 1), ($rda[$i]['name'] ?? '') . ($rda[$i]['num'] ?? ''));//
            $tmp->setValue("three#" . ($i + 1), $rda[$i]['number'] ?? '');//
            $tmp->setValue("four#" . ($i + 1), $rda[$i]['price'] ?? '');//
            $tmp->setValue("five#" . ($i + 1), $rda[$i]['number'] * $rda[$i]['price']);//总价格
        }
        foreach ($pay_service as $item) {
            $tmp->setValue("one#" . ($i + 1), $i + 1);//
            $tmp->setValue("two#" . ($i + 1), $item['name']);//
            $tmp->setValue("three#" . ($i + 1), '');//
            $tmp->setValue("four#" . ($i + 1), '');//
            $tmp->setValue("five#" . ($i + 1), $item['money']);//
            $i++;
        }

        $tmp->setValue("price", $workorder['money']);//总价格
        $tmp->setValue("tax", $workorder['tax']);//
        if (empty($workorder['collection_img'])) {
            $tmp->cloneBlock('img', 0);
        } else {
            $tmp->cloneBlock('img');
            foreach ($workorder['collection_img'] as $v) {
               //判断文件是否存在
                if(@file_get_contents($v['url']) == false){
                    $tmp->setImageValue("collection_img",'./assets/addons/qingdongams/mini/close.png');
                    continue;
                }
                $tmp->setImageValue("collection_img", ['path' => $v['url'], 'width' => 200, 'height' => 200]);
            }
        }
        if (empty($workorder['autograph_url'])) {
            $tmp->cloneBlock('autograph', 0);
        } else {
            $tmp->cloneBlock('autograph');
            $tmp->setImageValue("autograph_url", ['path' => $workorder['autograph_url'], 'width' => 200, 'height' => 200]);

        }
        if($workorder['owner_staff']){
            $tmp->setValue('staff_name', $workorder['owner_staff']['name']);
            $tmp->setValue('staff_mobile', $workorder['owner_staff']['mobile']);
            $tmp->setValue('staff_email', $workorder['owner_staff']['email']);

        }else{

            $tmp->setValue('staff_name','');
            $tmp->setValue('staff_mobile','');
            $tmp->setValue('staff_email','');
        }

        if (empty($workorder['collection_deposit'])) {
            $tmp->cloneBlock('account', 0);
        } else {
            $tmp->cloneBlock('account');
            $tmp->setValue('collection_deposit', $workorder['collection_deposit']);
            $tmp->setValue('collection_account', $workorder['collection_account']);
            $tmp->setValue('collection_name', $workorder['collection_name']);

        }

        //end 配置
        $filename = date('YmdHis') . '.docx';
        $fileurl = './docx/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new \addons\qingdongams\model\File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();
        $file = cdnurl($model::getUrl($lastid), true);

        $this->success('请求成功', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
    }

    //下载返厂维修
    public function downloadFanchang()
    {
        $id = input('id');
        $type = input('type', 'word');
        $workorder = WorkorderModel::where(['id' => $id])
            ->with(['customer', 'contacts', 'ownerStaff'])->find();
        if (empty($workorder)) {
            $this->error('不能为空');
        }
        if (empty($workorder['contacts'])) {
            $workorder['contacts'] = \addons\qingdongams\model\Contacts::where(['customer_id' => $workorder['customer_id']])->order('is_major desc')->field('id,customer_id,name,mobile,mobilecode,region')->find();
        }
        $workorder = $workorder->toArray();

        $tmp = new TemplateProcessor('assets/addons/qingdongams/phpword/fanchang.docx');
        \PhpOffice\PhpWord\Settings::setCompatibility(true);
        \PhpOffice\PhpWord\Settings::setOutputEscapingEnabled(true);
        $tmp->setValue('number', $workorder['workorder_number']);//订单编号
        $tmp->setValue('name', $workorder['customer']['name']);//乙方
        $tmp->setValue('mobile', $workorder['contacts']['mobile']);//乙方
        $tmp->setValue('date', $workorder['createtime']);//签订时间
        $tmp->setValue('desc', $workorder['desc']);//
        $tmp->setValue('matters', $workorder['matters']);//
        $tmp->setValue('appointment_time', $workorder['appointment_time']);//
        $product_name = '';
        foreach ($workorder['product_part'] as $v) {
            $product_name .= $v['product']['name'];
        }
        $tmp->setValue('product_name', $product_name);//
        //end 配置
        $filename = $workorder['customer']['name'] . '返厂维修单' . date('Ymdhis') . '.docx';
        $fileurl = './docx/' . date('Ymd') . '/';
        if (!file_exists($fileurl)) {
            mkdir($fileurl);
        }

        $tmp->setValue('owner_staff', $workorder['owner_staff']['name']);//
        $tmp->setValue('results', $workorder['results']);//
        $use_parts = '';
        foreach ($workorder['use_parts'] as $v) {
            $use_parts .= $v['name'] . '(' . $v['number'] . ');';
        };
        $tmp->setValue('use_parts', $use_parts);//
        $tmp->setValue('maintain', $workorder['maintain']);//
        $tmp->setValue('end_time', $workorder['end_time']);//
        $tmp->setValue('is_replace_0', $workorder['is_replace'] == 0 ? '✔️' : '');//
        $tmp->setValue('is_replace_1', $workorder['is_replace'] == 1 ? '✔️' : '');//
        $tmp->setValue('is_recovery_0', $workorder['is_recovery'] == 0 ? '✔️' : '');//
        $tmp->setValue('is_recovery_1', $workorder['is_recovery'] == 1 ? '✔️' : '');//

        $tmp->saveAs($fileurl . $filename);//另存为


        $model = new \addons\qingdongams\model\File();
        $data = [
            'types' => 'file',
            'name' => $filename,
            'save_name' => $fileurl . $filename,
            'size' => filesize($fileurl . $filename),
            'file_path' => trim($fileurl, '.') . $filename,
        ];

        $model->save($data);
        $lastid = $model->getLastInsID();
        $file = cdnurl($model::getUrl($lastid), true);
        if ($type == 'pdf') {
            $docfile = $_SERVER['DOCUMENT_ROOT'] . trim($data['save_name'], '.'); // word文件
            $pdfdir = $_SERVER['DOCUMENT_ROOT'] . trim($fileurl, '.'); // pdf文件
            $cmd = "export HOME=/tmp && libreoffice --headless -convert-to pdf {$docfile} -outdir {$pdfdir}";
            @exec($cmd);
            $pathinfo = pathinfo($file);
            $file = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.pdf';
            $filename = $pathinfo['filename'] . '.pdf';
        }

        $this->success('请求成功', ['file' => $file, 'id' => $lastid, 'filename' => $filename]);
    }

    /**
     * 生成二维码
     */
    public function qrcode()
    {
        $text = $this->request->get('text', 'hello world');

        //如果有安装二维码插件，则调用插件的生成方法
        if (class_exists("\addons\qrcode\library\Service") && get_addon_info('qrcode')['state']) {
            $qrCode = \addons\qrcode\library\Service::qrcode(['text' => $text]);
            $response = Response::create()->header("Content-Type", "image/png");

            header('Content-Type: ' . $qrCode->getContentType());
            $response->content($qrCode->writeString());
            return $response;
        } else {
            header("Content-type: image/png");
            $qr = QRCode::getMinimumQRCode($text);
            $im = $qr->createImage(8, 5);
            imagepng($im);
            imagedestroy($im);
            return;
        }
    }

    //获取车牌号
    public function getCarNumber()
    {
        $car_numbers = ConsumeDetail::where(['car_number' => ['neq', '']])->column('car_number');
        $car_numbers = array_unique($car_numbers);
        $this->success('请求成功', $car_numbers);
    }

    //获取结束公里数
    public function getEndMileage()
    {
        $car_number = input('car_number');
        $end_mileage = ConsumeDetail::where(['car_number' => $car_number,
            'end_mileage' => ['neq', '']])->order('id desc')->value('end_mileage');
        $this->success('请求成功', ['end_mileage' => $end_mileage ?? 0]);
    }

    //
    public function training_content()
    {
        $id = input('id');

        $data = [
            [
                'id' => 1,
                'name' => '培训内容',
                'data' => [
                    '使用、保养',
                ],
            ],

        ];
        $this->success('请求成功', $data);
    }

    //工单失败
    public function failWorkorder()
    {
        $id = input('id');
        $desc = input('desc');
        //
        $params = $this->request->post();
        if (empty($id)) {
            $this->error('参数错误');
        }
        $workorder = WorkorderModel::get($id);
        if (empty($workorder)) {
            $this->error('信息不存在');
        }
        Db::startTrans();
        try {
            WorkorderModel::failWorkorder($id,$desc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('提交成功');
    }

    //获取协助任务列表
    public function getAssistTaskList()
    {
        $relation_id = input('relation_id', '', 'intval');
        $relation_type = input('relation_type', 'proofing');
        $customer_id = input('customer_id');
        // 0未开始 1执行中2 已结束 3 已取消'
        $status = input('status', '');
        $event_type = input('event_type', '');
        $name = input('name', '');
        $limit = input("limit/d", 10);
        $where = [];
        if ($relation_id) {
            $where['relation_type'] = $relation_type;
            $where['relation_id'] = $relation_id;
        } else {
            $where['create_staff_id|staff_id'] = ['in', Staff::getMyStaffIds()];
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($event_type) {
            $where['event_type'] = ['like', "%{$event_type}%"];
        }
        if ($status) {
            $where['status'] = ['in', explode(',', $status)];
        }
        $where['type'] = 4;
        if ($name) {
            $where['title'] = ['like', '%' . $name . '%'];
        }
        $records = Event::where($where)->with([
            'staff',
            'customer',
            'comments',
        ])->order('id desc')->select();
        $records = collection($records)->toArray();

        $department = [];
        foreach ($records as $v) {
            Message::setRead(Message::ASSIST_EVENT_TYPE, $v['id'], $this->auth->id);
            $v['status'] = Event::getStatus($v['status']);
            $department[$v['staff']['department_id']][] = $v;
        }
        $data = [];
        foreach ($department as $id => $v) {
            $data[] = [
                'department_id' => $id,
                'department_name' => '',
                'data' => $v
            ];
        }
        $this->success('请求成功', $data);
    }

    public function getWorkorderDepartment()
    {
        $data = [];
        $this->success('请求成功', $data);
    }
}
